<template>
    <list-layout>
        <div slot="search">
            <el-form :model="queryParams" :inline="true" size="small" ref="queryForm" v-show="showSearch" label-width="88px">
                <el-row>

                    <el-col :span="6">
                        <!--            厂区：-->
                        <el-form-item :label="$t('mrbForm.mrbOrderNo')" prop="ncrOrder">
                            <el-input v-model="queryParams.ncrOrder" clearable :placeholder="$t('public.placeholder',{placeholder: $t('mrbForm.mrbOrderNo')})" @keyup.enter.native="handleQuery" />
                        </el-form-item>
                    </el-col>
                    <!--                    <el-col :span="6">
                        &lt;!&ndash;            厂区：&ndash;&gt;
                        <el-form-item :label="$t('mrbForm.initiateFactory')" prop="factoryName">
                            <el-input v-model="queryParams.factoryName" clearable :placeholder="$t('public.placeholder',{placeholder: $t('mrbForm.initiateFactory')})" @keyup.enter.native="handleQuery" />
                        </el-form-item>
                    </el-col>-->
                    <!--                    <el-col :span="6">
                        &lt;!&ndash;            供应商批次：：&ndash;&gt;
                        <el-form-item :label="$t('mrbForm.supplierBatchNo')" prop="lichn">
                            <el-input v-model="queryParams.lichn" clearable :placeholder="$t('public.placeholder',{placeholder: '供应商批次'})" @keyup.enter.native="handleQuery" />
                        </el-form-item>
                    </el-col>-->
                    <el-col :span="6">
                        <!--            批次：-->
                        <el-form-item :label="$t('mrbForm.InspectBatchNo')" prop="inspectionLotMark">
                            <el-input v-model="queryParams.inspectionLotMark" clearable :placeholder="$t('public.placeholder', {
                                    placeholder: $t('mrbForm.InspectBatchNo'),
                                  })" @keyup.enter.native="handleQuery" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <!--            物料编号-->
                        <el-form-item :label="$t('mrbForm.materialNo')" prop="materialCode">
                            <el-input v-model="queryParams.materialCode" :placeholder="
                                  $t('public.placeholder', {
                                    placeholder: $t('mrbForm.materialNo'),
                                  })
                                " clearable size="small" @keyup.enter.native="handleQuery" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <!--            物料名称：-->
                        <el-form-item :label="$t('mrbForm.materialName')" prop="materialName">
                            <el-input v-model="queryParams.materialName" clearable :placeholder="$t('public.placeholder',{placeholder: $t('mrbForm.materialName')})" @keyup.enter.native="handleQuery" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="6" align="left">
                        <!--            供应商编号：-->
                        <el-form-item :label="$t('mrbForm.supplierNo')" prop="supplierCode">
                            <el-input v-model="queryParams.supplierCode" clearable :placeholder="$t('public.placeholder',{placeholder: $t('mrbForm.supplierNo')})" @keyup.enter.native="handleQuery" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <!--            MRB状态：-->
                        <el-form-item :label="$t('mrbForm.mrbStatus')" prop="ncrStatus">
                            <el-select v-model="queryParams.ncrStatus" :placeholder="$t('public.select_holder',{select_holder: $t('mrbForm.mrbStatus')})">
                                <el-option label="全部" value=""></el-option>
                                <el-option v-for="dict in dict.type.NYIQC_NCR_STATUS" :key="dict.label" :label="dict.label" :value="dict.value" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <!--                    <el-col :span="6">
                        &lt;!&ndash;            成熟度：&ndash;&gt;
                        <el-form-item label="成熟度" prop="sapMaturity">
                            <el-select v-model="queryParams.sapMaturity" :placeholder="
              $t('public.select_holder', {
                select_holder: 'SAP成熟度',
              })
            " style="width: 100%" clearable size="small" multiple>
                                <el-option key="1" label="1" value="1"> </el-option>
                                <el-option key="2" label="2" value="2"> </el-option>
                                <el-option key="3" label="3" value="3"> </el-option>
                                <el-option key="6" label="6" value="6"> </el-option>
                            </el-select>

                        </el-form-item>
                    </el-col>-->

                    <!--                    <el-col :span="6">
                        &lt;!&ndash;            物料Q类：&ndash;&gt;
                        <el-form-item label="物料Q类" prop="qClass">
                            <el-select v-model="queryParams.qClass" :placeholder="$t('public.selectPl')+ '物料Q类'">
                                <el-option label="全部" value=""></el-option>
                                <el-option v-for="dict in dict.type.NYIQC_NCR_QCLASS" :key="dict.label" :label="dict.label" :value="dict.value" />
                            </el-select>
                        </el-form-item>
                    </el-col>-->
                    <!--                    <el-col :span="6">
                        &lt;!&ndash;            MRB分类：&ndash;&gt;
                        <el-form-item label="MRB分类" prop="ncrType">
                            <el-select v-model="queryParams.ncrType" :placeholder="$t('public.selectPl')+ 'MRB分类'">
                                <el-option label="全部" value=""></el-option>
                                <el-option v-for="dict in dict.type.NYIQC_NCR_CLASS" :key="dict.label" :label="dict.label" :value="dict.label" />
                            </el-select>
                        </el-form-item>
                    </el-col>-->

                    <el-col :span="6">
                        <!--            使用决策：-->
                        <el-form-item :label="$t('mrbForm.useDecision')" prop="usingDecision">
                            <el-select v-model="queryParams.usingDecision" :placeholder="$t('public.selectPl')+ $t('mrbForm.useDecision')">
                                <el-option v-for="dict in dict.type.NYIQC_NCR_DECISION" :key="dict.label" :label="dict.label" :value="dict.value" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item :label="$t('basicData.baseName')" prop="baseId">
                            <el-select v-model="queryParams.baseId" filterable clearable :placeholder="$t('public.placeholder',{placeholder:$t('basicData.baseName')})" >
                                <el-option
                                v-for="item in baseList"
                                :key="item.baseId"
                                :label="item.baseName"
                                :value="item.baseId">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="6">
                        <!-- 发起人姓名/工号 -->
                        <el-form-item :label="$t('inventoryManagement.nameEmployeeNumber')" prop="initiatorName">
                            <el-input v-model="queryParams.initiatorName" :disabled="type === 2" :placeholder="$t('public.placeholder',{placeholder:$t('inventoryManagement.nameEmployeeNumber')})" size="small" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <!-- 供应商名称 -->
                        <el-form-item :label="$t('basicData.supplierName')" prop="supplierName">
                            <el-input v-model="queryParams.supplierName" :placeholder="$t('public.placeholder',{placeholder:$t('basicData.supplierName')})" size="small" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <!--            物料分类：-->
                        <el-form-item :label="$t('formValidation.materialClassification')" prop="categoryIds">
                            <el-cascader
                                v-model="queryParams.categoryIds"
                                ref="cascader"
                                :options="materialClassification"
                                :props="{multiple: true, expandTrigger:'hover',emitPath:false,checkStrictly: true,value:'id',label:'label' }"
                                clearable
                            ></el-cascader>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <!--            创建时间：-->
                        <el-form-item :label="$t('mrbForm.createTime')" prop="createTime">
                            <el-date-picker v-model="dateRange" size="small" style="width: 220px" value-format="yyyy-MM-dd" type="daterange" autocomplete="off" range-separator="-" :start-placeholder="$t('public.startDate')" :end-placeholder="$t('public.endDate')"></el-date-picker>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="6">
                                   <!-- 检验完成时间: -->
                        <el-form-item :label="$t('mrbForm.checkedTime')" prop="expectedDate ">
                            <el-date-picker v-model="expectedDate" size="small" style="width: 220px" value-format="yyyy-MM-dd" type="daterange" autocomplete="off" range-separator="-" :start-placeholder="$t('public.startDate')" :end-placeholder="$t('public.endDate')"></el-date-picker>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                                   <!-- MRB发起时间: -->
                        <el-form-item :label="$t('mrbForm.MRBTime')" prop="initiatorTime  ">
                            <el-date-picker v-model="initiatorTime" size="small" style="width: 220px" value-format="yyyy-MM-dd" type="daterange" autocomplete="off" range-separator="-" :start-placeholder="$t('public.startDate')" :end-placeholder="$t('public.endDate')"></el-date-picker>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col align="center">

                        <el-form-item class="right-btns">
                            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">{{$t('public.query')}}</el-button>
                            <el-button icon="el-icon-refresh" class="resectBtn" size="mini" @click="resetQuery">{{$t('public.reset')}}</el-button>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>

        </div>
        <div class="app-container">
            <div class="container-header">
                <div class="header-left">
                    {{ $t('mrbForm.mrbForm') }}
                </div>
            </div>
            <el-row :gutter="10" class="table-action-wrap btnGroup">
                <el-col :span="1.5">
                    <el-button class="exportitemBtn" size="mini" @click="handleExport" v-hasPermi="['ny-iqc:ncrReview:export']"><img src="@/assets/images/icons/daochu.png" alt=""> {{$t('public.export')}}</el-button>
                    <el-button size="mini" v-hasPermi="['ny-iqc:handled:initiate']" class="exportitemBtn" @click="handleNcr" :disabled="single"><img src="@/assets/images/icons/addNCR.png" alt="" />
                        {{ $t('mrbForm.initiateMRB')}}</el-button>
                    <el-button size="mini" v-hasPermi="['ny-iqc:handled:flowDispose']" class="exportitemBtn"
                    @click="handleNcrApprove" :disabled="checkedStatus!='0'"><img src="@/assets/images/icons/approve.png" alt="" />
                        {{$t('inspectionManagement.approval')}}</el-button>
                    <el-button size="mini"   class="exportitemBtn" @click="submitCostForm" :disabled="single">
                      {{$t('formValidation.originationFeePassThrough')}}
                    </el-button>
                </el-col>
            </el-row>
            <div class="container-table">
                <el-table :height="tableHeight" :row-class-name="tableRowClassName" border v-loading="loading" :data="typeList" @selection-change="handleSelectionChange">

                    <el-table-column type="selection" width="55" align="center" />
                    <!--          序号-->
                    <el-table-column :label="$t('public.serialNum')" type="index" width="55" align="center" />

                    <!--          MRB单号-->
                    <el-table-column :label="$t('mrbForm.mrbOrderNo')" align="left" prop="ncrOrder" minWidth="160" show-overflow-tooltip />

                    <!--          MRB分类-->
                    <el-table-column :label="$t('mrbForm.mrbType')" align="left" prop="ncrType" minWidth="160" show-overflow-tooltip />

                    <!--          物料编号-->
                    <el-table-column :label="$t('mrbForm.materialNo')" align="left" prop="materialCode" minWidth="160" show-overflow-tooltip />

                    <!--          物料Q类-->
                    <!--                    <el-table-column label="物料Q类" align="left" prop="qclass" minWidth="160" show-overflow-tooltip>
                        <template slot-scope="scope">
                            <span v-if="scope.row.qclass == 1">{{$t('defectIncoming.QClass')}}</span>
                            <span v-if="scope.row.qclass == 2">{{$t('defectIncoming.unQClass')}}</span>
                        </template>
                    </el-table-column>-->

                    <!--          物料名称-->
                    <el-table-column :label="$t('mrbForm.materialName')" align="left" prop="materialName" minWidth="160" show-overflow-tooltip />
                    <!-- <el-table-column label="【SAP】成熟度" align="left" prop="sapMaturity" width="100" show-overflow-tooltip /> -->
                    <!--          供应商批次-->
                    <!--                    <el-table-column :label="$t('mrbForm.supplierBatchNo')" align="left" prop="lichn" minWidth="160" show-overflow-tooltip />-->

                    <!--          检验批次号批次-->
                    <el-table-column :label="$t('mrbForm.InspectBatchNo')" align="left" prop="inspectionLotMark" minWidth="160" show-overflow-tooltip />

                    <!--          来料数量-->
                    <el-table-column :label="$t('mrbForm.incomingQuantity')" align="left" prop="batchAmount" minWidth="160" show-overflow-tooltip />
                    <el-table-column :label="$t('mrbForm.unit')" align="left" prop="mengeneinh" min-width="100" :show-overflow-tooltip="true" />
                    <!--          供应商编号-->
                    <el-table-column :label="$t('mrbForm.supplierNo')" align="left" prop="supplierCode" minWidth="160" show-overflow-tooltip />
                    <!--          发起厂区-->
                    <!--                    <el-table-column :label="$t('mrbForm.initiateFactory')" align="left" prop="launchFactory" minWidth="160" show-overflow-tooltip />-->
                    <!--          MRB状态-->
                    <el-table-column :label="$t('mrbForm.mrbStatus')" align="left" prop="ncrStatus" minWidth="160" show-overflow-tooltip>
                        <template slot-scope="scope">
                            <span>{{formatNCRStatus(scope.row)}}</span>
                        </template>
                    </el-table-column>
                    <el-table-column :label="$t('mrbForm.mrbOaStatus')" align="left" prop="ncrOaStatus" minWidth="160" show-overflow-tooltip>
                        <template slot-scope="scope">
                            <span>{{formatNCROaStatus(scope.row)}}</span>
                        </template>
                    </el-table-column>
                    <!--          是否遏制-->
                    <!--                    <el-table-column :label="$t('mrbForm.isContain')" align="left" prop="whetherStem" minWidth="160" show-overflow-tooltip>
                        <template slot-scope="scope">
                            <span v-if="scope.row.whetherStem == 1">{{$t('public.yes')}}</span>
                            <span v-if="scope.row.whetherStem == 2">{{$t('public.no')}}</span>
                        </template>
                    </el-table-column>-->
                    <!--          班次-->
                    <!--                    <el-table-column :label="$t('mrbForm.classes')" align="left" prop="shift" minWidth="160" show-overflow-tooltip />-->
                    <!--          使用决策-->
                    <el-table-column :label="$t('mrbForm.useDecision')" align="left" prop="usingDecision" minWidth="160" show-overflow-tooltip>
                        <template slot-scope="scope">
                            <span>{{usingDecisionFilter(scope.row)}}</span>
                        </template>
                    </el-table-column>
                    <!--          创建时间-->
                    <!-- <el-table-column label="送检日期" align="left" prop="deliveryDate" minWidth="160" show-overflow-tooltip /> -->
                    <!--                  质量整改单状态-->
                    <!-- <el-table-column :label="$t('mrbForm.RectificationStatus')" align="center" prop="status" minWidth="160" show-overflow-tooltip>
                        <template slot-scope="scope">
                            {{scope.row.status=='0'?'':scope.row.status}}
                        </template>
                    </el-table-column> -->
                    <!--                    <el-table-column label="特采理由" align="left" prop="launchFactory" minWidth="160" show-overflow-tooltip />-->
                    <!--                    <el-table-column label="特采时间" align="left" prop="launchFactory" minWidth="160" show-overflow-tooltip />-->
                    <!--                    <el-table-column label="使用客户" align="left" prop="launchFactory" minWidth="160" show-overflow-tooltip />-->
                    <!--                    <el-table-column label="异常内容" align="left" prop="launchFactory" minWidth="160" show-overflow-tooltip />-->
                    <!--                    <el-table-column label="控制措施" align="left" prop="launchFactory" minWidth="160" show-overflow-tooltip />-->
                    <el-table-column :label="$t('inventoryManagement.purchaser')" align="left" prop="initiatorName" minWidth="160" show-overflow-tooltip />
                    <el-table-column :label="$t('public.createDate')" align="left" prop="createTime" minWidth="160" show-overflow-tooltip />
                    <el-table-column :label="$t('mrbForm.checkedTime')" align="left" prop="inspectionEndTime" minWidth="160" show-overflow-tooltip />
                    <el-table-column :label="$t('mrbForm.MRBTime')" align="left" prop="initiatorTime" minWidth="160" show-overflow-tooltip />
                    <el-table-column :label="$t('public.opera')" fixed="right" align="left" width="100">
                        <template slot-scope="scope">
                            <div class="action-wrap">
                                <!-- <table-body-btn type="edit" name="审批" v-if="scope.row.ncrProcessId&&scope.row.ncrProcessId.length>0&&scope.row.ncrStatus!=='1'" @click.native="handleApprove(scope.row)" v-hasPermi="['ny-iqc:ncrReview:getInfo']" /> -->
                                <!-- <table-body-btn type="add" :name="$t('mrbForm.RectificationForm')" @click.native="handleAdd(scope.row)" v-hasPermi="['ny-iqc:ncrReview:getInfo']" /> -->
                                <table-body-btn type="gwview" :name="$t('home.view')" @click.native="lookMrbDetail(scope.row)" v-hasPermi="['ny-iqc:ncrReview:getInfo']" />
                            </div>
                        </template>
                    </el-table-column>
                </el-table>

                <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" layout="total, sizes, prev, pager, next, jumper" />
            </div>

            <!-- 审批 -->
            <el-dialog :title="$t('inventoryManagement.approval')" :visible.sync="isShowApprovalDialog" center top="14vh" width="520px" append-to-body :fullscreen="fullscreen" @close="resetAuditForm">
                <el-form :model="auditForm" ref="auditForm" label-position="top" :rules="auditRules">
                    <el-form-item :label="$t('inventoryManagement.isPassApproval')" prop="status">
                        <el-radio-group v-model="auditForm.status">
                            <el-radio label="1">{{$t("inventoryManagement.pass")}}</el-radio>
                            <el-radio label="2">{{$t("inventoryManagement.reject")}}</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item ref="reviewFileField" :label="$t('mrbForm.attachment')" prop="reviewFile">
                        <file-upload class="file-upload-box" :limit="1" bizType="ANNEX_FILE_UPLOAD" :otherList="annexFileList" :bizId="fileId" v-model="auditForm.reviewFile" @change="changeAnnexFile"></file-upload>
                    </el-form-item>
                    <el-form-item :label="$t('inventoryManagement.rejectReason')" prop="planRemark">
                        <el-input type="textarea" :placeholder="$t('public.placeholder', { placeholder: $t('inventoryManagement.rejectReason')})" v-model="auditForm.planRemark" maxlength="1000">
                        </el-input>
                    </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button type="primary" @click="submitAudit" icon="el-icon-check" size="small">{{ $t("public.define") }}</el-button>
                </div>
            </el-dialog>

            <!-- 查看 弹框 -->
            <detail :visible.sync="visible" v-model="form" :type="dialogType" @refresh="getList()"></detail>

            <dialog-rectify :visible.sync="visibleRectify" :data="form"></dialog-rectify>

        </div>
    </list-layout>
</template>

<script>
import {refreshCache} from '@/api/basic/dict/type'
// import { factoryList } from '@/api/masterdata/factory'
import { baseList } from '@/api/masterdata/base'
import {getTree} from '@/api/basic/materialClassification'
import {
  delMaterialMessage,
  FinalNode,
  flowDispose,
  flowDisposeCheck,
  getNcrReviewDetail,
  getProcessById,
  listNcrReview,
  getApproval
} from '@/api/inventoryManagement/ncrReview'
import {templateInfo} from '@/api/flowTemplate/flowTemplate'
import SelectUserDialog from '@/views/components/SelectUserDialog'
import SelectNodeDialog from '@/views/components/SelectNodeDialog'
// import {listAllMaterialMessageMessage } from "@/api/inventoryManagement/gaugeMessage";
import {mapGetters, mapState} from 'vuex'
import Detail from './detial.vue'
import DialogRectify from './dialogRectify.vue'
import { geFileByBiz } from '@/api/file/file'
import { undoToDo } from "@/api/notificationManager/notificationManager"

//基础数据-物料信息管理
export default {
    name: 'MRBList',
    dicts: [
        'NYIQC_NCR_STATUS',
        'NYIQC_NCR_SHIFT',
        'NYIQC_NCR_DECISION',
        'NYIQC_BATCH',
        'NYIQC_NCR_QCLASS',
        'NYIQC_NCR_CLASS',
        'NYIQC_AUDIT_RESULT',
        'NYIQC_FLOW_APPROVALSTATUS'
    ],
    components: { Detail, DialogRectify, SelectUserDialog, SelectNodeDialog },
    computed: {
        ...mapGetters(['userId', 'name', 'deptName']),
        ...mapState({
            isFold: (state) => state.app.isFold,
        }),
        checkedStatus(){
            // ncrStatus=0
            if(this.ids.length!==1){
                return -1
            }
            var list= this.typeList.filter(item=>item.id==this.ids[0])
            if(list.length==1){
                return list[0].ncrStatus
            }
            return -1
        }
    },
    watch: {
        isFold(val) {
            if (val === true) {
                this.tableHeight = 'calc(100vh - 308px)'
            } else {
                this.tableHeight = 'calc(100vh - 466px)'
            }
        },
    },
    data() {
        return {
            materialClassification:[],
            baseList:[],
            dialogType: 1, //1:新增  2：编辑 3：查看
            dialogForm: {
                lotUse: '',
            },
            processCode: '0',
            operateType: 'add',
            lastStep: false,
            deviceOptions: [],
            factoryOptions: [],
            approvalOpen: false,
            tableHeight: 'calc(100vh - 308px)',
            direction: 'rtl',
            addInspection: false,
            visible: false,
            visibleRectify: false,
            drawer: false,
            approvalOpen: false,
            viewModel: {
                inspectionInformation: '0',
            },
            editModel: {
                inspectionInformation: '0',
            },
            approvalForm: {
                status: '1',
                textarea: '',
            },
            selBtn: 1,
            // 遮罩层
            loading: true,
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            // 字典表格数据
            typeList: [],
            userlist: [],
            // 弹出层标题
            title: '发起MRB',
            // 是否显示弹出层
            open: false,
            // 日期范围
            dateRange: [],
            // 日期范围
            expectedDate: [],
            // 日期范围
            initiatorTime: [],

            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 20,
                factoryName: '',
                lichn: '',
                lot: '',
                materialName: '',
                supplierCode: '',
                ncrStatus: '',
                materialCode: '',
                sapMaturity: '',
                shift: '',
                lotUse: '',
                usingDecision: '',
                qClass: '',
                ncrType: '',
                createTime: '',
                initiatorName:'',
                baseId:'',
                supplierName:'',
                categoryIds:'',
            },
            // 表单参数
            form: undefined,

            fullscreen: false,
            isShowApprovalDialog: false,
            auditForm: {
                status: null,
                reviewFile: '',
                planRemark: ''
            },
            // 表单校验
            auditRules: {
                status: [
                    {
                        required: true,
                        message: '状态不能为空',
                        trigger: 'change',
                    },
                ],
                reviewFile: [
                    {
                        required: true,
                        message: '附件不能为空',
                        trigger: 'change',
                    },
                ],
                planRemark: [
                    {
                        required: true,
                        message: '备注不能为空',
                        trigger: 'blur',
                    },
                ],
            },
            fileId: '',
            unPassStageList: [],
            annexFileList: [],
            ncrStatus: '' // ncr状态
        }
    },
    created(){
      let id = this.$route.query.id;
      let scene = this.$route.query.scene;
      //回调调用 OA待办转已办 接口
      if (id != undefined && scene != undefined) {
        undoToDo(id, scene).then((res) => {
          if (res.code != 200) {
            this.$modal.msgError(res.msg)
          }
        })
        this.queryParams.id = id
      }
        baseList().then((response) => {
            if (response.rows) {
                this.baseList = response.rows
            }
        })
        getTree().then((response) => {
        this.materialClassification = response.data
      })
    },
    mounted() {
        if (this.$route.query.status) {
            this.queryParams.usingDecision = this.$route.query.status
        }
        if (this.$route.query.uniqueId) {
            this.queryParams.id = this.$route.query.uniqueId
        }
        this.getList()
    },
    activated() {
        if (this.$route.query.status) {
            this.queryParams.usingDecision = this.$route.query.status
        }
        if (this.$route.query.uniqueId) {
            this.queryParams.id = this.$route.query.uniqueId
        }
        this.getList()
    },
    methods: {

        submitCostForm(){
            var  approvalModel=this.selectRows[0]
            var data={
                mrbOrder:approvalModel.ncrOrder,
                lot:approvalModel.lot,//批次号:
                inspectionLotMark:approvalModel.inspectionLotMark,//检验批号
                customerName:approvalModel.customer//客户名称

            }
            console.log(data)
            window.history.pushState(data,'', '/ny-iqc/costShift/costForm/0')
        },
        // 重置表单
        resetAuditForm() {
            this.auditForm = {
                ...this.auditForm,
                status: null,
                planRemark: '',
                reviewFile: ''
            }
            this.annexFileList = [];
            this.$refs.auditForm.resetFields();
        },

        // 修改附件
        changeAnnexFile(fileList) {
            this.auditForm = {
                ...this.auditForm,
                reviewFile: fileList[0].id
            }
            this.$refs.reviewFileField.clearValidate();
        },

        // 获取文件
        geFileByBiz(id) {
            geFileByBiz({ bizId: id }).then((res) => {
                res.data.forEach((io, i) => {
                    const len = this.annexFileList.length;
                    if (io.bizType === 'ANNEX_FILE_UPLOAD' && len === 0 ) {
                        this.annexFileList.push(io);
                    }
                })

                this.auditForm = {
                    ...this.auditForm,
                    reviewFile: this.annexFileList
                }
            })
        },
        // 打开审批弹框
        openApproveDialog() {
            getNcrReviewDetail(this.fileId).then((response) => {
                const { ncrStatus, mrbRemark } = response.data;

                if(ncrStatus === '0') {
                    this.isShowApprovalDialog = true;
                    this.auditForm = {
                        status: null,
                        planRemark: mrbRemark
                    }
                    this.geFileByBiz(this.fileId);

                } else {
                    this.$modal.msgWarning('只有状态为处理中的才能审核!')
                }
            })

        },
        // 确认审核
        submitAudit() {
            this.$refs['auditForm'].validate((valid) => {
                if (valid) {
                    this.loading = true;
                    getApproval({
                        ...this.auditForm,
                        id: this.fileId,
                        mrbRemark: this.auditForm.planRemark,
                        ncrStatus: this.auditForm.status
                    }).then((res) => {
                        this.loading = false;
                        this.$modal.msgSuccess('审批成功!')
                        this.isShowApprovalDialog = false;
                        this.getList()

                        this.$refs['auditForm'].resetFields();
                        this.annexFileList = [];
                    }).catch(err => {
                        this.loading = false;
                    })
                }
            })
        },

        handleAddProcess(scope) {
            let row = JSON.parse(JSON.stringify(scope.row))
            row.handledUserName = undefined
            row.handledUserPedt = undefined
            row.handledUserPost = undefined
            this.userlist.splice(scope.$index + 1, 0, row)

            // this.viewModel.handledList.push({
            //     nodeName: null,
            //     handledUserName: null,
            //     handledUserPedt: null,
            //     handledUserPost: null,
            // })
        },

        handleConfirm() {
            this.approvalOpen = false
        },
        nodeCallback(taskDefKey) {
            this.$refs.detailForm.validateField('nodeName')
        },
        transferCallback(row) {

            this.$refs.detailForm.validateField('transferUserName')
        },
        formatStatus(e) {
            if (e) {
                let obj = this.dict.type.NYIQC_FLOW_APPROVALSTATUS.find(
                    (item) => {
                        return item.value === e
                    }
                )
                if (obj) {
                    return obj.label
                } else {
                    return ''
                }
            } else {
                return ''
            }
        },

        userDataCallback(row, index) {
            this.userlist[index].handledUserPedt = row.deptName
            this.userlist[index].handledUserPost = row.post
            this.userlist[index].handledUserId = row.userId
        },

        // 发起MRB
        async handleNcr() {
            if (this.ids.length === 0) {
                this.$modal.msgWarning(
                    this.$t('inspectionManagement.pleaseSelectOne')
                )
                return
            }
            this.lastStep = false
            this.operateType = 'add'
            this.processCode = '0'
            this.title = '发起MRB';

            this.fileId = this.ids[0];
            const fileId = this.ids[0];
            this.dialogType = '1';
            const dialogType = this.dialogType;

            const response = await getNcrReviewDetail(fileId);

            const { ncrStatus } = response.data;
            if(ncrStatus === '3') {
                this.$router.push(`/inventory/mrbReview/${fileId}?viewType=${dialogType}`);
            } else {
                this.$modal.msgWarning('只有待发起状态的才能发起MRB!')
            }
        },
        // mrb详情
        async getMrbInfo(id) {
            // const id = '1676518792269664257';
            getNcrReviewDetail(id ? id : this.ids[0]).then((response) => {
                const { ncrStatus, mrbRemark } = response.data;

                this.ncrStatus = ncrStatus;
            })
        },
        // 发起审批
        handleNcrApprove(){
            if(Array.isArray(this.ids) && this.ids.length > 0){
                const fileId = this.ids[0];
                this.$router.push(`/inventory/mrbReview/${fileId}?viewType=4`);
            }else {
                this.$modal.msgWarning(
                    this.$t('inspectionManagement.pleaseSelectOne')
                )
            }
        },

        handleDeleteProcess(row) {
            if (row.$index === 0) {
                this.$modal.msgWarning('请至少保留一条会签!')
                return
            }
            this.userlist.splice(row.$index, 1)
        },
        handleApprove(row) {
            this.lastStep = false
            this.title = '审批'
            this.operateType = 'edit'
            this.processCode = row.ncrProcessId
            flowDisposeCheck({ processId: row.ncrProcessId }).then(
                (response) => {
                    if (response.code === 200) {
                        this.taskId = response.data
                        this.approvalOpen = true
                        this.getMrbInfo(row.id)
                        this.getProcessById(row.id)
                        this.FinalNode(row.ncrProcessId)
                    }
                }
            )
        },
        FinalNode(processId) {
            FinalNode({ processId: processId }).then((response) => {
                if (response.data) {
                    this.lastStep = true
                    this.approvalModel.approvalStatus = '2'
                }
            })
        },
        handleView(row) {
            this.approvalOpen = true
            this.processCode = row.ncrProcessId
            this.operateType = 'view'
            this.title = '查看'
            this.getMrbInfo(row.id)
            this.getProcessById(row.id)
        },
        getProcessById(id) {
            getProcessById({
                businessId: id,
            }).then((response) => {
                let userlist = []
                response.data.forEach((io) => {
                    let obj = io
                    obj.checked = false
                    userlist.push(obj)
                })
                this.userlist = userlist
            })
        },
        // 查看详情
        lookMrbDetail({id}) {
            const dialogType = '3';
            this.$router.push(`/inventory/mrbReview/${id}?viewType=${dialogType}`);
        },

        getNodeListByAppNameProcKey() {
            templateInfo({ procKey: 'nyiqc.mrb.review' }).then((response) => {
                this.userlist = response.data.handledList
            })
            // getNodeListByAppNameProcKey({
            //     procKey: 'ny-iqc.mrb.review',
            //     appName: 'ny-iqc',
            // }).then((response) => {
            //     let userList = []
            //     response.data.forEach((io) => {
            //         let obj = io
            //         obj.nodeName = io.name
            //         userList.push(obj)
            //     })
            //     this.userlist = userList
            // })
        },
        formatNCRStatus(row) {

            const current = this.dict.type.NYIQC_NCR_STATUS.find((io) => {
                return io.value === row.ncrStatus
            })
            return current ? current.label : ''
        },
        formatNCROaStatus(row) {

            return row.oaStatus === '0' ? '待审核' : row.oaStatus === '1' ? '审核通过' : row.oaStatus === '2' ? '审核失败' : row.oaStatus === null ? '' : '';
        },
        filterParams(p) {
            if (p && p.length) {
                let index = (p || []).findIndex((i) => i === '全部')
                index >= 0 ? p.splice(index, 1) : p
                return p.join(',')
            } else {
                return ''
            }
        },
        usingDecisionFilter(row) {
            if (row.usingDecision) {
                let io = this.dict.type.NYIQC_NCR_DECISION.find((item) => {
                    return item.value == row.usingDecision
                })
                if (io) {
                    return io.label
                } else {
                    return ''
                }
            } else return ''
        },
        drawerClose() {
            this.drawer = false
        },
        /** 查询字典类型列表 */
        getList() {
            this.loading = true
            let params = JSON.parse(JSON.stringify(this.queryParams))
            // params.sapMaturity = params.sapMaturity.join(',')
            params.lotUse = this.filterParams(params.lotUse)
            // ,this.expectedDate,this.initiatorTime
            let objParams = this.addDateRange(this.addDateRange(this.addDateRange(params, this.dateRange),this.expectedDate,true,{filed:['expectedBeginDate','expectedEndDate']}),this.initiatorTime,true,{filed:['initiatorBeginTime','initiatorEndTime']})
            listNcrReview(objParams).then(
                (response) => {
                    if (response.code == 200 && response.rows) {
                        this.typeList = response.rows
                        this.total = response.total
                        this.loading = false
                        this.tableHeight = this.isFold
                            ? 'calc(100vh - 308px)'
                            : 'calc(100vh - 466px)'
                    }
                }
            )
        },
        // 取消按钮
        cancel() {
            this.open = false
            this.reset()
        },
        tableRowClassName({ row, rowIndex }) {
            if (row.isHighLight === true) {
                return 'rowHighLight' //若isHighLight为true，则使用“rowHighLight”样式
            } else {
                return ''
            }
        },
        // 表单重置
        reset() {
            this.form = {
                dictId: undefined,
                dictName: undefined,
                dictType: undefined,
                status: '0',
                remark: undefined,
            }

            this.resetForm('form')
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1
            this.getList()
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.dateRange = []
            this.expectedDate = []
            this.initiatorTime = []
            // this.queryParams.baseId = ''
            this.resetForm('queryForm')
            this.queryParams.id = undefined
            this.handleQuery()
        },
        /** 新增按钮操作 */
        handleAdd(row) {
            this.form = row
            this.visibleRectify = true
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.selectRows = selection
            this.ids = selection.map((item) => item.id);
            this.fileId = this.ids[0];

            this.typeList.forEach((io, index) => {
                if (this.ids.includes(io.id)) {
                    io.isHighLight = true
                } else {
                    io.isHighLight = false
                }
            })
            this.single = selection.length != 1
            this.multiple = !selection.length
            // this.single = selection.length!=1
            // this.multiple = !selection.length
        },

        deviceRemoteMethod(e) {
            listAllMaterialMessageMessage({ deviceName: e }).then((res) => {
                this.deviceOptions = res.data
            })
        },
        handleDeviceChange(e) {
            this.queryParams.deviceName = e.join(',')
        },
        handleMaterialMessageTypeChange(e) {
            this.queryParams.gaugeType = e.join(',')
        },
        /** 删除按钮操作 */
        handleDelete(row) {
            const dictIds = (row && row.id) || this.ids
            this.$modal
                .confirm('是否确认删除id为"' + dictIds + '"的数据项？')
                .then(function () {
                    return delMaterialMessage(dictIds)
                })
                .then(() => {
                    this.getList()
                    this.$modal.msgSuccess(this.$t('processDefinition.successfullyDeleted'))
                })
                .catch(() => {})
        },
        /** 编辑按钮操作 */
        handleEdit(row) {
            this.dialogType = 2
            this.form = row
            this.visible = true
        },
        /** 关闭抽屉操作 */
        handleClose(row) {
            this.drawer = false
        },
        /** 导出按钮操作 */
        handleExport() {
            this.download(
                '/ny-iqc/ncrReview/export',
                {
                    ...this.queryParams,
                },
                `ncrApproval_${new Date().getTime()}.xlsx`
            )
        },
        /** 刷新缓存按钮操作 */
        handleRefreshCache() {
            refreshCache().then(() => {
                this.$modal.msgSuccess('刷新成功')
            })
        },
    },
}
</script>
<style lang="scss" scoped>
.file-upload-box {
    line-height: 20px;
}
::v-deep .el-form-item__label {
    width: 101px !important;
}
::v-deep .el-date-editor.el-input, .el-date-editor.el-input__inner{
    width:205px !important;
}
::v-deep .el-form-item__content {
    line-height: 32px;
}
::v-deep .el-upload__tip {
    line-height: 20px;
}
::v-deep .el-card {
    // padding-top: 20px;
    border: 0px;
    box-shadow: 0px 2px 6px 0px rgba(0, 0, 0, 0.08);
    border-radius: 4px;
    padding-bottom: 20px;
}
::v-deep .el-aside {
    padding: 0;
    margin-bottom: 0;
}
.content-style {
    border: 0px;
    box-shadow: 0px 2px 6px 0px rgba(0, 0, 0, 0.08);
    border-radius: 2px;
    background-color: white;
    margin-top: 10px;
}
::v-deep .el-button-group .selBtn {
    background: #fff;
    border: 1px solid #0b7be3;
    color: #0b7be3;
}
::v-deep .el-button-group .unselBtn {
    background: #fff;
    border: 1px solid #ededf2;
    color: #666666;
}
.header-left {
    font-size: 14px;
    font-family: PingFangSC-Semibold, PingFang SC;
    font-weight: 600;
    color: #333333;
    padding: 3px 0 10px;
    display: inline-flex;
    justify-content: center;
    border-bottom: 2px solid #0b7be3;
}
.header-right {
    float: right;
}
.container-header {
    border-bottom: 1px solid #ededf2;
}
.container-table {
    float: left;
    //margin-top:6px;
    width: 100%;
}
.mb8 {
    float: left;
    margin-top: 6px;
    width: 100%;
}
.drawer-footer {
    display: flex;
    position: relative;
    z-index: 9999;
    bottom: -40px;
    height: 40px;
    justify-content: center;
    width: 100%;
}
.drawer-close {
    background: #f7f8fa;
    border-color: #f7f8fa;
}

.right-btns ::v-deep .el-button {
    margin-top: 0;
}
.app-container {
    padding: 0;
}
.table-action-wrap {
    padding: 12px 0;
}
::v-deep .rowHighLight {
    background: oldlace;
}
::v-deep .el-dialog__body {
    max-height: 500px;
    overflow-y: auto;
}

.select-style {
    width: 100%;
}
</style>
